<!--
 * @Description: router-view
 * @Author bianpengfei
 * @create 2021/3/23 22:26
 -->
<template>
  <div class="relative flex-1">
    <BRouterViewCache
      :class="['g-app-view', 'relative', 'main__content', _isExternal && 'div--webkit--scrollbar--none']"
      :mode="_mode"
      :max="keepAliveMaxNum"
      :transitionName="_transitionNameOwn"
      @route-change="routeChange"
      ref="cacheV2"
    ></BRouterViewCache>
    <div class="g-app-view__footer">
      <i class="bpf-icon-touxiang iconfont-pc text-30px"></i>
      <div class="ml-14px">
        <span class="mr-10px">
          <span>登陆人员：</span>
          <span>张三</span>
        </span>
        <span class="mr-10px">
          <span>登陆时间：</span>
          <span>2022-11-02 19:26:56</span>
        </span>
        <span class="mr-10px">
          <span>登陆总时长：</span>
          <span>{{ totalLoginTime }}</span>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { get, call, sync } from 'vuex-pathify'
import { generateNavAttr } from '@bianpengfei/b-ui/lib/_util/router-cache'
import { changeElementPrimaryColor } from '@/libs/utils/theme.js'
import { keepAliveMaxNum } from '@/setting'
import { isObject, debounceDtor, isArrayEmpty, parentNodesInTree, isArray } from '@bianpengfei/utils'
import { diffTimeFormat } from '@libs/utils/common'

export default {
  data() {
    return {
      keepAliveMaxNum,
      totalLoginTime: '' // 登陆总时长
    }
  },

  computed: {
    _isExternal: get('app/isExternal'),
    _navArr: sync('app/navArr'),
    _layout: get('app/layout'),
    _theme: get('app/theme'),
    _primaryColor: get('app/primaryColor'),
    _breadcrumbShow: get('app/breadcrumbShow'),
    _breadcrumb: sync('app/breadcrumb'),
    _menus: get('app/menus'),
    _menusList: get('app/menusList'),
    _transitionName: get('app/transitionName'),
    _transitionEnable: get('app/transitionEnable'),
    _weekMode: get('app/weekMode'),
    _routingStack: sync('app/routingStack'),
    _routeDirection: sync('app/routeDirection'),
    _routePosition: sync('app/routePosition'),

    _transitionNameOwn() {
      if (['mobile'].includes(this._transitionName)) {
        const tempConf = {
          backward: 'pop-out',
          forward: 'pop-in'
        }
        return tempConf[this._routeDirection]
      }
      return this._transitionName
    },

    _mode() {
      return ['mobile'].includes(this._transitionName) ? '' : 'out-in'
    }
  },

  watch: {
    /*监听导航tag 变化*/
    _navArr: {
      handler(newVal, oldVal) {
        if (newVal.length < oldVal.length) {
          const removeView = oldVal.find((o) => {
            return newVal.findIndex((i) => i.fullPath === o.fullPath) < 0
          })
          if (removeView && removeView.meta?.cache) {
            this.$nextTick(() => {
              this.$refs.cacheV2 && this.$refs.cacheV2.rmCacheRoute(removeView.fullPath)
            })
          }
        }
      }
    },

    /*监听布局变化*/
    _layout: {
      handler(newVal, oldVal) {
        const el = document.body
        const prefix = 'layout--'
        el.classList.forEach((v) => {
          if (String(v).includes(prefix)) {
            el.classList.remove(String(v))
          }
        })
        el.classList.add(`${prefix}${newVal}`)
        if (oldVal) {
          const instant = this.$message.loading('正在更换布局...')
          setTimeout(() => {
            instant.close()
            setTimeout(() => {
              this.$message.success('更换布局成功')
            }, 200)
          }, 1200)
        }
      },
      immediate: true
    },

    /*监听主题变化*/
    _theme: {
      handler(newVal) {
        const el = document.body
        const prefix = 'theme--'
        el.classList.forEach((v) => {
          if (String(v).includes(prefix)) {
            el.classList.remove(String(v))
          }
        })
        // 如果是公司布局，就不加载theme
        if (['mandala'].includes(this._layout)) return
        el.classList.add(`${prefix}${newVal}`)
      },
      immediate: true
    },

    /*监听饿了么主题颜色 变化*/
    _primaryColor: {
      handler(newVal, oldVal) {
        changeElementPrimaryColor(newVal, () => {
          if (oldVal) {
            const instant = this.$message.loading('正在加载主题中...')
            setTimeout(() => {
              instant.close()
              setTimeout(() => {
                this.$message.success('更换主题成功')
              }, 200)
            }, 1000)
          }
        })
      },
      immediate: true
    },

    /*色弱模式*/
    _weekMode: {
      handler(newVal, oldVal) {
        let className = 'week-mode'
        const el = document.body
        el.classList.forEach((v) => {
          if (String(v).includes('week-mode')) {
            el.classList.remove(String(v))
          }
        })
        newVal && el.classList.add(className)
        oldVal && el.classList.remove(className)
      },
      immediate: true
    }
  },

  created() {
    // window.APP_PAGE_ROUTER_VIEW = this
    this.$baseEventBus.$on('reload-router-view', (route) => {
      this.$refs.cacheV2 && this.$refs.cacheV2.reload(route)
    })

    // 14时6分23秒
    console.log(this.$dayjs('2022-11-07 16:44:10').valueOf())
    console.log(new Date('2022-11-07 16:44:10').valueOf())
  },

  mounted() {
    this.containerDOM ||= document.querySelector('.main__content')
    window.addEventListener('resize', this.handleResize)
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', this.handleResize)
      clearInterval(this._timer)
    })
    this.handleResize()
    const getDiffDate = () => {
      this.totalLoginTime = diffTimeFormat(new Date('2022-11-07 16:44:10').valueOf())
    }
    getDiffDate()
    this._timer = setInterval(getDiffDate, 1000)
  },

  methods: {
    _addNavArrItem: call('app/addNavArrItem'),
    _removeNavItem: call('app/removeNavItem'),

    getDiffDate() {},

    /**
     * 路由变化
     * @param route
     * @param routeDirection
     * @param toFullPath
     * @param fromFullPath
     * @param routingStack
     * @param routingStackHistory
     */
    routeChange({ route, routeDirection, toFullPath, fromFullPath, routingStack, routingStackHistory }) {
      this._routeDirection = routeDirection
      this._routingStack = routingStack

      // 1、设置面包屑
      let breadcrumb = parentNodesInTree({
        tree: this.loopMenusAttrs(JSON.parse(JSON.stringify(this._menus))),
        id: route.path,
        props: { id: 'path', children: 'children' }
      })
      if (!breadcrumb?.length) {
        breadcrumb = parentNodesInTree({
          tree: this.loopMenusAttrs(JSON.parse(JSON.stringify(this._menus))),
          id: route.name,
          props: { id: 'name', children: 'children' }
        })
      }
      if (!breadcrumb || isArrayEmpty(breadcrumb)) {
        breadcrumb = [generateNavAttr(this.$route)]
      }
      this._breadcrumb = breadcrumb
      if (!breadcrumb.length) {
        breadcrumb = [generateNavAttr(this.$route)]
      }
      this._breadcrumb = breadcrumb

      // 2、保证缓存的页面回退，原来的滚动位置
      if (!this.containerDOM) this.containerDOM = document.querySelector('.main__content')
      const scrollTop = this._routePosition[toFullPath]?.y
      if (scrollTop && this.containerDOM) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.containerDOM.scroll({
              top: scrollTop,
              left: 0,
              behavior: 'smooth'
            })
          }, 400)
        })
      }
    },

    @debounceDtor(300)
    handleResize() {
      const scrollView = document.querySelector('.main__content')
      document.querySelector('.main__content').style.height = `calc(100vh - ${
        scrollView.getBoundingClientRect()?.top + 45
      }px)`
    },

    /**
     * 递归处理menus
     * @param menus
     * @returns {*[]}
     */
    loopMenusAttrs(menus = []) {
      menus = menus
        .filter((v) => !v.meta?.hidden)
        .map((v) => {
          v.index = v.path || v.fullPath || v.ID
          if (isObject(v.meta)) {
            Object.keys(v.meta).forEach((key) => {
              v[key] = v.meta[key]
            })
          }
          if (v?.isSingle) {
            v.path = v.redirect
            delete v.children
          }
          if (v.children && Array.isArray(v.children)) {
            // v.children = v.child
            // delete v.child
            v.children = this.loopMenusAttrs(v.children)
          }
          return v
        })
      return menus
    }
  }
}
</script>
